// pages/refund/refund.js
const orderService = require('../../../../api/orderService.js')
const request = require('../../../../api/request.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatarUrl: null,
    imageUrls: [],
    goodsList:[],
    orderId: '',
    inputText: '',
    canRefund: true,
    refundNumber: 0,
    allRedund: false,
    labels: [{
      id: 0,
      text: '不想要了',
      select: false
    }, {
      id: 1,
      text: '我买错了',
      select: false
    }, {
      id: 2,
      text: '购买的商品缺货',
      select: false
    }, {
      id: 3,
      text: '店员态度不好',
      select: false
    }, {
      id: 4,
      text: '果品质量不好',
      select: false
    }, {
      id: 5,
      text: '其他',
      select: false
    }],
    type: 'submit',
    count: 5
  },
  chooseImage: function() {
    var that = this;
    let count = that.data.count - that.data.imageUrls.length
    if (count > 0) {
      wx.chooseImage({
        count: count, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function(res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          var tempFilePaths = res.tempFilePaths
          //启动上传等待中...  
          wx.showToast({
            title: '正在上传...',
            icon: 'loading',
            mask: true,
            duration: 200000
          })
          console.log(tempFilePaths)
          var filePaths = that.data.imageUrls
          tempFilePaths.forEach(ele => {
            wx.uploadFile({
              url: request.BASE_URL + '/dfs/upload', //仅为示例，非真实的接口地址
              filePath: ele,
              name: 'file',
              formData: {
                'user': 'test'
              },
              success: function(res) {
                try {
                  var data = res.data
                  let tempData = JSON.parse(data)
                  console.log(tempData)
                  filePaths.push(tempData.data.url)
                  that.setData({
                    //将临时变量赋值给已经在data中定义好的变量
                    avatarUrl: filePaths,
                    imageUrls: filePaths
                  })
                  wx.hideToast()
                } catch (error) {
                  console.log(error)
                  wx.showToast({
                    title: error.message,
                    icon: 'none',
                    duration: 200000
                  })
                }
              },
              fail: function(e) {
                console.log(e.message)
              }
            })
          });
        }
      })
    } else {
      wx.showToast({
        title: '最多只能上传5张哦~',
        icon: 'none',
        duration: 200000
      })
    }
  },
  clickLabels: function(val) {
    const that = this
    let labels = this.data.labels
    const id = val.currentTarget.dataset.id
    labels.forEach((item, index) => {
      if (item.id === id) {
        if (item.select === false) {
          item = {
            ...item,
            select: true
          }
        } else {
          item = {
            ...item,
            select: false
          }
        }
        labels[index] = item
        that.setData({
          labels: labels
        })
      }
    })
  },
  handelTextArea: function(e) {
    console.log(e.detail)
    if (e.detail.cursor < 200) {
      this.setData({
        inputText: e.detail.value
      })
    } else if (e.detail.cursor === 200) {
      this.setData({
        inputText: e.detail.value
      })
      wx.showToast({
        title: '详细信息最多不超过200个字符哦~',
        icon: 'none',
        duration: 2000
      })
    } else {

    }

  },
  backOrder: function() {
    wx.navigateBack({
      delta: 1
    })
  },
  refundSubmit: function() {
    const that = this
    if (this.data.canRefund) {
      let tempImageUrls = ''
      const avatarUrl = this.data.avatarUrl
      const labels = this.data.labels
      const inputText = this.data.inputText
      if (avatarUrl) {
        tempImageUrls = avatarUrl.join(",")
      }
      let tempText = ''
      labels.forEach(item => {
        if (item.select) {
          if (tempText === '') {
            tempText = item.text
          } else {
            tempText = tempText + ',' + item.text
          }
        }
      })
      let goodsArr = that.data.goodsList
      let tempList = []
      goodsArr.forEach(item => {
        if (item.checked === true) {
          tempList.push({
            productId: item.productId,
            productNumber: item.productNumber
          })
        }
      })
      if ((inputText !== '' && inputText != null) || tempText !== '') {
        let postData = {
          applyReason: this.data.inputText,
          descriptionImageUrls: tempImageUrls, //描述图片,以","分割
          orderId: this.data.orderId,
          refundDetails: tempList
        }
        if (tempText !== '') {
          postData = {
            ...postData,
            applyReason: tempText + ',' + postData.applyReason
          }
        }
        console.log(postData)
        orderService.createRefund(postData).then(res => {
          console.log(res)
          wx.setNavigationBarTitle({
            title: '退款申请'
          })
          that.setData({
            type: 'success'
          })
        }).catch(error => {
          console.log(error)
          wx.showToast({
            title: error.message,
            icon: 'none',
            duration: 2000
          })
        })
      } else {
        wx.showToast({
          title: '请填写退款理由，谢谢~',
          icon: 'none',
          mask: true,
          duration: 2000
        })
      }
    } else {
      wx.showModal({
        title: '温馨提示',
        content: '您近期已经提交了相关商品的退款单，我们的工作人员正在努力审核哦，审核结果将第一时间通知您，请勿重复提交，谢谢~',
        success: function(res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },
  getOrderDetails: function() {
    let orderId = this.options.orderId
    orderService.getDetailsById(orderId).then(res => {
      console.log(res)
      let itemSatus = res.status
      let tempList = []
      res.products.forEach(item => {
        tempList.push({
          ...item,
          productNumber: 0
        })
      })
      this.setData({
        orderId: res.id,
        memberName: res.memberName,
        mobile: res.mobile,
        goodsList: tempList,
        address: res.province + res.city + res.district + res.address,
        storeName: res.storeName,
        createTime: res.createTime,
        cashTotal: res.cashTotal,
        orderAmount: res.orderAmount,
        cashDeductTotal: res.cashDeductTotal,
        remark: res.remark,
        storeAddress: res.storeAddress,
        shipmentType: res.shipmentType,
        shipmentAmount: res.shipmentAmount,
        canRefund: res.canRefund
      })
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  // checkbox监听事件
  checkboxChange: function(e) {
    if (e.detail.value.length === this.data.goodsList.length) {
      this.setData({
        checkedAll: true
      })
    } else {
      this.setData({
        checkedAll: false
      })
    }
    let tempData = this.data.goodsList;
    tempData.forEach(ele => {
      ele.checked = false;
      ele.productNumber = 0;
    })
    console.log(e.detail.value)
    let tempNum = 0;
    e.detail.value.forEach(item => {
      tempData.forEach(ele => {
        if (item === ele.productId) {
          ele.checked = true;
          ele.productNumber = ele.productNum;
          tempNum = tempNum + ele.productNumber
        }
      })
    })
    this.setData({
      goodsList: tempData,
      refundNumber: tempNum
    })
    this.checkAllRefund()
  },
  // 全选点击事件
  checkboxAllChange: function(e) {
    let tempData = this.data.goodsList;
    let tempNum = 0
    if (e.detail.value.length === 0) {
      tempData.forEach((item, index) => {
        item.checked = false;
        item.productNumber = 0
      })
      this.setData({
        goodsList: tempData,
        refundNumber: tempNum
      })
    } else {
      tempData.forEach((item, index) => {
        item.checked = true;
        item.productNumber = item.productNum
        tempNum = tempNum + item.productNumber
      })
      this.setData({
        goodsList: tempData,
        refundNumber: tempNum
      })
    }
    this.checkAllRefund()
  },
  // 数量减事件
  handleReduce: function(e) {
    let tempData = this.data.goodsList;
    let allNum = this.data.refundNumber
    let checkedCount = 0
    tempData.forEach(item => {
      if (item.productId === e.currentTarget.dataset.id) {
        if (item.productNumber > 0) {
          item.productNumber--
            allNum--
            if (item.productNumber > 0) {
              item.checked = true
            } else {
              item.checked = false
            }
        }
      }
      if (item.checked) {
        checkedCount++
      }
    })
    this.setData({
      goodsList: tempData,
      refundNumber: allNum
    })
    if (checkedCount === this.data.goodsList.length) {
      this.setData({
        checkedAll: true
      })
    } else {
      this.setData({
        checkedAll: false
      })
    }
    this.checkAllRefund()
  },
  // 数量加事件
  handleAdd: function(e) {
    let tempData = this.data.goodsList;
    let allNum = this.data.refundNumber;
    let checkedCount = 0
    tempData.forEach(item => {
      if (item.productId === e.currentTarget.dataset.id) {
        if (item.productNumber < item.productNum) {
          item.productNumber++
            allNum++
            if (item.productNumber > 0) {
              item.checked = true
            } else {
              item.checked = false
            }
        }
      }
      if (item.checked) {
        checkedCount++
      }
    })
    this.setData({
      goodsList: tempData,
      refundNumber: allNum
    })
    if (checkedCount === this.data.goodsList.length) {
      this.setData({
        checkedAll: true
      })
    } else {
      this.setData({
        checkedAll: false
      })
    }
    this.checkAllRefund()
  },
  checkAllRefund: function() {
    const tempList = this.data.goodsList
    let allRedund = true
    tempList.forEach(item => {
      if (item.productNumber !== item.productNum) {
        allRedund = false
      }
    })
    this.setData({
      allRedund: allRedund
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.hideShareMenu()
    if (options.orderId) {
      this.setData({
        orderId: options.orderId
      })
      this.getOrderDetails()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})